<template>
  <span>
    <el-button type="primary" plain icon="el-icon-upload" style="margin-left: 10px;" @click="handleUploadData">{{ btnText }}</el-button>
    <el-dialog
      :title="title+(hasSpend==0?'':('(已耗时'+hasSpend+'s)'))"
      :visible.sync="dialogVisible"
      custom-class="upload-dialog"
      :show-close="false"
      :before-close="handleClose">
      <el-row style="margin-bottom: 10px;">
        <el-col :span="18">
          <el-upload
            :show-file-list="false"
            action=""
            accept=".xls"
            :auto-upload="false"
            :on-change="handleUploadChange"
            :multiple="false">
            <el-button
              v-loading="uploadLoading"
              type="primary">
              选择导入的数据(.xls)
            </el-button>
          </el-upload>
        </el-col>
        <el-col :span="24">
          <div style="margin-top: 10px;font-size: 12px;">
            <div>是否保存源文件：
              <el-radio-group v-model="fileSave">
                <el-radio :label="0">不保存</el-radio>
                <el-radio :label="1">保存</el-radio>
              </el-radio-group>
            </div>
            <slot name="query" />
            <div style="margin-top: 10px;margin-bottom: 10px;">
              导入数据前需先下载文件模板，导入数据文件大小不能超过3M，且按照模板进行数据填充，
              <export-drop-down
                type="text"
                :class-name="className"
                accept="xls"
                :async="true"
                :list-query="{
                  ...listQuery,
                  template:true
                }"
                tooltip="下载模板"
                :title="title+'示例模板'"
                style="margin-top:10px" />
            </div>
            <div class="color-danger">
              <p> (1)、仅运行导入*.xls格式文件</p>
              <p>(2)、若导入出错，提示“eg XSSF instead of HSSF”，请将excel另存为一份即可</p>
            </div>
          </div>
        </el-col>
      </el-row>
      <div class="color-danger m-b-20" style="margin-top: 10px;font-size: 14px;">已耗时:{{ hasSpend }}s</div>
      <el-card class="box-card m-b-20 log-card" style="flex: 1;">
        <div slot="header" class="clearfix">
          <span>任务执行日志</span>
        </div>
        <div class="import-desc">
          <ol>
            <li v-for="(item,index) in logs" :key="index" :class="item.success?'color-primary' : 'color-danger'">{{ index+1 }}、{{ item.time | formatDate('yyyy-MM-dd hh:mm:ss') }}&nbsp;&nbsp;&nbsp;{{ item.message }}。</li>
          </ol>
        </div>
      </el-card>
    </el-dialog>
  </span>
</template>
<script>
export default {
  props: {
    className: {
      type: String,
      required: true
    },
    listQuery: {
      type: Object,
      required: false,
      default: () => {
        return {}
      }
    },
    title: {
      type: String,
      default: '数据导入'
    },
    btnText: {
      type: String,
      default: '导入'
    },
    module: {
      type: String,
      required: false,
      default: ''
    },
    actions: {
      type: Array,
      required: false,
      default: () => {
        return ['importData', 'getImportProcessStatus']
      }
    }
  },
  data() {
    return {
      fileSave: 1,
      sizeLimit: 3,
      dialogVisible: false,
      uploadLoading: false,
      uploadLoadingText: '文件上传中...',
      percentage: 0,
      hasSpend: 0,
      stepStart: 0,
      hasSpendInterval: null,
      realTimeProgressInterval: null,
      logs: [],
      fileSaveUUID: ''
    }
  },
  created() {

  },
  methods: {
    handleClose(done) {
      if (this.uploadLoading) {
        this.msgWarning('当前有未完成的数据导入任务,建议不要关闭对话框')
        this.log('当前有未完成的数据导入任务,建议不要关闭对话框')
      } else {
        this.$confirm('确认关闭？').then(_ => {
          done()
        }).catch(_ => {})
      }
    },
    handleUploadData() {
      this.dialogVisible = true
      this.percentage = 0
      this.hasSpend = 0
      this.logs = []
    },
    handleUploadChange(file) {
      this.logs = []
      this.uploadLoading = true
      var ext = file.name.substr(file.name.lastIndexOf('.') + 1)
      var exts = ['xls']
      if (!exts.includes(ext)) {
        this.msgWarning('请选择.xls格式文件!')
        this.log('请选择.xls格式文件!')
        this.uploadLoading = false
        return
      }
      const isLt = file.size / 1024 / 1024 < this.sizeLimit
      if (!isLt) {
        this.msgWarning('文件大小不能超过 ' + this.sizeLimit + 'MB!')
        this.log('文件大小不能超过 ' + this.sizeLimit + 'MB!')
        this.uploadLoading = false
        return
      }
      const formData = new FormData()
      formData.append('file', file.raw)
      formData.append('className', this.className)
      formData.append('loading', false)
      formData.append('ext', ext)
      formData.append('fileSave', this.fileSave)
      for (var item in this.listQuery) {
        formData.append(item, this.listQuery[item])
      }
      this.log(`您已选择数据文件: ${file.name}，上传中...`, true)
      this.stepStart = new Date().getTime()
      this.setStepInterval()

      this.$store.dispatch(this.actions[0], formData).then((res) => {
        this.log(`文件${file.name},上传成功,任务ID：${res}`, true)
        this.getImportProcessStatus(res)
        this.realTimeProgressInterval = setInterval(() => {
          this.getImportProcessStatus(res)
        }, 1000)
      }).catch((err) => {
        console.log(err)
        this.uploadLoading = false
        this.log(`文件${file.name}，上传失败,原因${err.data ? err.data : err}`)
        this.clearImportProcess()
      })
    },
    getImportProcessStatus(taskId) {
      this.$store.dispatch(this.actions[1], { taskId: taskId, className: this.className, loading: false }).then(response => {
        var describe = response.describe
        var progress = response.progress
        switch (progress) {
          case 'FINISH':
            this.log(describe, true)
            this.clearImportProcess()
            this.uploadLoading = true
            this.log('3s后自动关闭对话框!', true)
            setTimeout(() => {
              this.dialogVisible = false
              this.uploadLoading = false
              this.$emit('success', this.fileSaveUUID)
            }, 3000)
            break
          case 'ERROR':
            this.log(describe)
            this.clearImportProcess()
            break
          case 'DOWN':
            this.log(`文件下载标识：${describe}`, true)
            this.fileSaveUUID = describe
            break
          default:
            this.log(describe, true)
            break
        }
      }).catch((err) => {
        this.log(`获取实时进度,原因${err}`)
        this.clearImportProcess()
      })
    },
    clearImportProcess() {
      this.uploadLoading = false
      if (this.realTimeProgressInterval) {
        clearInterval(this.realTimeProgressInterval)
      }
      if (this.hasSpendInterval) {
        clearInterval(this.hasSpendInterval)
      }
    },
    setStepInterval() {
      this.hasSpendInterval = setInterval(() => {
        this.hasSpend = (new Date().getTime() - this.stepStart) / 1000
      }, 1000)
    },
    log(message, isSuccess = false) {
      this.logs.unshift({
        message: message,
        success: isSuccess,
        time: new Date().getTime()
      })
    }
  }
}
</script>
<style lang="scss">
.upload-dialog{
  width: 600px;
  margin: 100px auto 100px auto !important;
  height: calc(100vh - 110px);
  .el-dialog__body{
    height: calc(100% - 60px);
    display: flex;
    flex-direction: column;
  }
}
.import-desc{
    color: #aaa;
    li{
        margin-bottom: 8px;
    }
  }
  .log-card .el-card__body{
    overflow: auto;
  }
</style>
